const pool=require('../../Model/query')

const jwt = require('jsonwebtoken');
const {JWT_SECRET,encrypt}=require('../../config/userConfig')
const  login=(req, res)=> {
  const {userName,password,captcha}=req.body
  if(!userName||!password){
    return  res.send({
      code:400,
      msg:'userName和password不能为空'
    });
  }
  if(!captcha){
    return  res.send({
      code:400,
      msg:'请输入验证码'
    });
  }
  if(!req.session.captcha){
    return  res.send({
      code:400,
      msg:'验证码过期,请重新获取'
    });
  }
  if(!captcha || (req.session.captcha && req.session.captcha.toLowerCase()!=captcha.toLowerCase())){
    return  res.send({
      code:400,
      msg:'验证码错误'
    });
  }
  const sql = 'SELECT * FROM user WHERE userName = ? AND password = ?';
  pool(sql,[userName, encrypt(password)]).then(res1=>{
    if(res1.length==0){
      return res.send({
        code:500,
        msg:'登录账号或密码不正确'
      });
    }
    const token = jwt.sign({ userName,password }, JWT_SECRET, { expiresIn: '1h' });
    res.send({
      code:200,
      data:{
        token
      },
      msg:'登录成功'
    });
  }).catch(()=>{
    res.send({
      code:500,
      msg:'登录失败'
    });
  })
}

const  register=(req, res)=> {
  let {userName,password,nickName,mobile,avator,sex=1,createTime=new Date()}=req.body
  const sql = `INSERT INTO user (
  userName,password,nickName,mobile,avator,sex,createTime)
  VALUES(?,?,?,?,?,?,?)`
  if(!userName||!password){
    return  res.send({
      code:400,
      msg:'userName和password不能为空'
    });
  }
  password=encrypt(password)
  pool(sql,[userName,password,nickName,mobile,avator,sex,createTime]).then(res1=>{
    res.send({
      code:200,
      msg:'注册成功'
    });
  }).catch(()=>{
    res.send({
      code:500,
      msg:'注册失败'
    });
  })
}

module.exports={
  login,
  register
}